<template>
  <div class="system-user-dialog-container">
    <el-dialog v-model="state.dialog.isShowDialog" :title="state.dialog.title" width="769px">
      <el-form ref="userDialogFormRef" :model="state.ruleForm" :rules="rules" label-width="90px" size="default">
        <el-row :gutter="35">
          <el-col :lg="12" :md="12" :sm="12" :xl="12" :xs="24" class="mb20">
            <el-form-item label="账户名称" prop="loginName">
              <el-input v-model="state.ruleForm.loginName" :disabled="formReadonly" clearable
                        placeholder="请输入账户名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="12" :md="12" :sm="12" :xl="12" :xs="24" class="mb20">
            <el-form-item label="用户名称" prop="userName">
              <el-input v-model="state.ruleForm.userName" :disabled="formReadonly" clearable
                        placeholder="请输入用户名称"></el-input>
            </el-form-item>
          </el-col>

          <el-col :lg="12" :md="12" :sm="12" :xl="12" :xs="24" class="mb20">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="state.ruleForm.phone" :disabled="formReadonly" clearable
                        placeholder="请输入手机号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="12" :md="12" :sm="12" :xl="12" :xs="24" class="mb20">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="state.ruleForm.email" :disabled="formReadonly" clearable
                        placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="12" :md="12" :sm="12" :xl="12" :xs="24" class="mb20">
            <el-form-item label="性别" prop="sex">
              <el-select v-model="state.ruleForm.sex" :disabled="formReadonly" class="w100" clearable
                         placeholder="请选择">
                <el-option label="帅哥" value="帅哥"></el-option>
                <el-option label="美女" value="美女"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="12" :md="12" :sm="12" :xl="12" :xs="24" class="mb20">
            <el-form-item label="账户过期" prop="expirationDate">
              <el-date-picker v-model="state.ruleForm.expirationDate" :disabled="formReadonly" class="w100"
                              placeholder="请选择"
                              type="date" value-format="YYYY-MM-DD HH:mm:ss"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :lg="12" :md="12" :sm="12" :xl="12" :xs="24" class="mb20">
            <el-form-item label="用户状态" prop="active">
              <el-switch v-model="state.ruleForm.active" :active-value="1" :disabled="formReadonly" :inactive-value="0"
                         active-text="启用" inactive-text="禁用" inline-prompt></el-switch>
            </el-form-item>
          </el-col>
          <el-col v-show="state.dialog.type !== 'add'" :lg="24" :md="24" :sm="24" :xl="24" :xs="24" class="mb20">
            <el-form-item label="关联角色" prop="roleIdList">
              <el-select v-model="state.ruleForm.roleIdList" :disabled="!formReadonly" class="w100" clearable multiple
                         placeholder="请选择">
                <el-option v-for="item in state.roleList" :key="item.id" :label="item.roleName"
                           :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="24" :md="24" :sm="24" :xl="24" :xs="24" class="mb20">
            <el-form-item label="个性签名" prop="personalSign">
              <el-input v-model="state.ruleForm.personalSign" :disabled="formReadonly" maxlength="150"
                        placeholder="请输入用户描述"
                        type="textarea"></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="24" :md="24" :sm="24" :xl="24" :xs="24" class="mb20">
            <el-form-item label="用户描述" prop="remarks">
              <el-input v-model="state.ruleForm.remarks" :disabled="formReadonly" maxlength="150"
                        placeholder="请输入用户描述"
                        type="textarea"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
				<span class="dialog-footer">
					<el-button size="default" @click="onCancel">取 消</el-button>
					<el-button size="default" type="primary" @click="onSubmit(userDialogFormRef)">
						{{ state.dialog.submitTxt }}
					</el-button>
				</span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" name="systemUserDialog" setup>
import {computed, nextTick, reactive, ref} from 'vue';
import {userApi} from '/@/api/sys/user';
import {roleApi} from '/@/api/sys/role';
import type {FormInstance, FormRules} from 'element-plus';
import {ElMessage} from 'element-plus';
import type {RoleType} from '/@/api/sys/types';
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 定义变量内容
const userDialogFormRef = ref();
const state = reactive({
  ruleForm: {
    loginName: '', // 账户名称
    userName: '', // 用户昵称
    phone: '', // 手机号
    personalSign: '',
    email: '', // 邮箱
    sex: '', // 性别
    avatar: '', // 头像
    password: '', // 账户密码
    expirationDate: '', // 账户过期
    active: 1, // 用户状态
    remarks: '', // 用户描述
    roleSign: '', // 关联角色
    roleIdList: [], // 角色id列表
    department: [] as string[], // 部门
  },
  deptData: [] as DeptTreeType[], // 部门数据
  dialog: {
    isShowDialog: false,
    type: '',
    title: '',
    submitTxt: '',
  },
  roleList: [] as RoleType[],
});
const rules = reactive<FormRules>({
  loginName: [{required: true, message: '不能为空', trigger: 'blur'}],
  userName: [{required: true, message: '不能为空', trigger: 'blur'}],
  phone: [{required: true, message: '不能为空', trigger: 'blur'}],
  email: [{required: true, message: '不能为空', trigger: 'blur'}],
  sex: [{required: true, message: '不能为空', trigger: 'change'}],
  expirationDate: [{required: true, message: '不能为空', trigger: 'blur'}],
});
// 打开弹窗
const openDialog = (type: string, row: RowUserType) => {
  state.dialog.type = type;
  state.dialog.isShowDialog = true;
  if (type === 'edit') {
    state.dialog.title = '修改用户';
    state.dialog.submitTxt = '修 改';
  } else if (type === 'add') {
    state.dialog.title = '新增用户';
    state.dialog.submitTxt = '新 增';
  } else if (type === 'role') {
    state.dialog.title = '分配角色';
    state.dialog.submitTxt = '分 配';
    userApi().userRoleList(row.id).then((res) => {
      state.ruleForm.roleIdList = (res.data || []).map((a: any) => a.roleId as number);
    })
    roleApi().roleList().then((res) => {
      state.roleList = res.data || []
    })
  }
  nextTick(() => {
    if (type === 'add') {
      // 清空表单，此项需加表单验证才能使用
      userDialogFormRef.value.resetFields();
    } else {
      state.ruleForm = Object.assign(state.ruleForm, row);
    }
  });
};
// 关闭弹窗
const closeDialog = () => {
  state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
  closeDialog();
};
// 提交
const onSubmit = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  // 角色分配
  if (state.dialog.type === 'role') {
    onAssignRoles();
    return;
  }
  formEl.validate((valid) => {
    if (valid) {
      if (state.dialog.type === 'add') {
        userApi()
            .addRecord(state.ruleForm)
            .then((res) => {
              if (res && res.code === 200) {
                ElMessage.success(res.msg || '新增成功');
                closeDialog();
                emit('refresh');
              }
            });
      } else if (state.dialog.type === 'edit') {
        userApi()
            .updateRecord(state.ruleForm)
            .then((res) => {
              if (res && res.code === 200) {
                ElMessage.success(res.msg || '修改成功');
                closeDialog();
                emit('refresh');
              }
            });
      }
    }
  });
};
// 角色分配
const onAssignRoles = () => {
  userApi().assignRoles(state.ruleForm).then((res) => {
    closeDialog();
    ElMessage.success(res.msg || '角色分配成功');
    emit('refresh');
  })
}
const formReadonly = computed(() => {
  return state.dialog.type !== 'add' && state.dialog.type !== 'edit'
})
// 暴露变量
defineExpose({
  openDialog,
});
</script>
